package com.whzykj.job;

import java.util.Date;
import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.IPlugin;

/**
 * 实现作业的调度
 * @author yuanfang
 */
public class QuartzPlugin implements IPlugin {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private SchedulerFactory sf = null;
	private Scheduler sched = null;
	
//	private static QuartzPlugin quartz=null;
//
//	private QuartzPlugin() {}
//	
//	//单例---得到唯一的QuartzPlugin实例对象
//	public static QuartzPlugin getInstance(){
//		if(quartz==null){
//			quartz=new QuartzPlugin();
//		}
//		return quartz;
//	}
	
	private static class LazyHolder {
		private static final QuartzPlugin INSTANCE = new QuartzPlugin();
	}

	private QuartzPlugin() {
	}

	public static final QuartzPlugin getInstance() {
		
		return LazyHolder.INSTANCE;
	}
     
	public boolean start() {
		sf = new StdSchedulerFactory();
		try {
			sched = sf.getScheduler();
		} catch (SchedulerException e) {
			new RuntimeException(e);
		}
		//取表sys_job，并对表中所有配置的定时任务做处理
		
		Class<? extends Job> clazz = this.getJobClass("com.whzykj.job.OrderJob");
		// 配置调度、触发器
		JobDetail jobDetail = JobBuilder.newJob(clazz).build();
		String cron_rule=" 0 0/1 * * * ? ";
		CronScheduleBuilder builder = CronScheduleBuilder.cronSchedule(cron_rule);
		Trigger trigger = TriggerBuilder.newTrigger().startNow().withSchedule(builder).build();
		Date ft = null;
		try {
			ft=sched.scheduleJob(jobDetail, trigger);
			sched.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return true;
	}
	
	@SuppressWarnings("unchecked")
	private Class<? extends Job> getJobClass(String className) {
		try {
			Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(className);
			if (Job.class.isAssignableFrom(jobClass) == false) {
				throw new IllegalArgumentException(
						"Job class must implement the Job interface.");
			}
			return jobClass;
		} catch (ClassNotFoundException e) {
			logger.error(e.getMessage());
			throw new IllegalArgumentException(className
					+ "ClassNotFoundException!");
		}
	}

	/**
	 * 停止所有的任务
	 */
	public boolean stop() {
		try {
			sched.shutdown();
		} catch (SchedulerException e) {
			logger.error("关闭定时Job任务异常！！", e);
			return false;
		}
		return true;
	}
	
}